<?php

namespace app\api\controller\v1\team;

use app\Request;
use think\facade\Db;

class Team
{

    public function hasTeam(Request $request) {
        try {
            $uid = $request->uid();
            $teamModel = app()->make(\app\model\crud\Team::class);
            $hasTeam = $teamModel->whereFindInSet('user_ids',$uid)
                ->with('adminBaoming')
                ->find();

            if ($hasTeam) {
                // 格式化数据，包含队长报名信息
                $formattedTeam = [
                    'id' => $hasTeam['id'],
                    'name' => $hasTeam['name'],
                    'avatar' => $hasTeam['avatar'],
                    'num' => $hasTeam['num'],
                    'total_num' => $hasTeam['total_num'],
                    'admin_uid' => $hasTeam['admin_uid'],
                    'user_ids' => $hasTeam['user_ids'],
                    'university' => $hasTeam['university'],
                    'admin_baoming' => $hasTeam['admin_baoming'] ? [
                        'name' => $hasTeam['admin_baoming']['name'] ?? '',
                        'school_card' => $hasTeam['admin_baoming']['school_card'] ?? '',
                        'mobile' => $hasTeam['admin_baoming']['mobile'] ?? '',
                        'game_id' => $hasTeam['admin_baoming']['game_id'] ?? '',
                        'sancang' => $hasTeam['admin_baoming']['sancang'] ?? ''
                    ] : null,
                    'create_time' => $hasTeam['create_time']
                ];

                return app('json')->success(['hasTeam' => $formattedTeam]);
            } else {
                return app('json')->success(['hasTeam' => null]);
            }
        } catch (\Exception $e) {
            return app('json')->fail('检查队伍信息失败：' . $e->getMessage());
        }
    }

    public function createTeam(Request $request) {
        $uid = $request->uid();
        $teamModel = app()->make(\app\model\crud\Team::class);
        $data = $request->post();
        $data['user_ids'] = $uid;
        $data['admin_uid'] = $uid;
        $teamModel->save($data);
        return app('json')->success(100001);
    }

    public function updateTeam(Request $request) {
        $uid = $request->uid();
        $teamModel = app()->make(\app\model\crud\Team::class);
        $data = $request->post();

        // 检查是否有ID，如果有则进行更新操作
        if (!empty($data['id'])) {
            $teamId = $data['id'];
            $team = $teamModel->where('id', $teamId)->find();

            if (!$team) {
                return app('json')->fail('队伍不存在');
            }

            // 检查是否为队长，只有队长才能更新队伍信息
            if ($team['admin_uid'] != $uid) {
                return app('json')->fail('您不是该队伍的队长，无权更新队伍信息');
            }

            // 移除ID字段，避免更新主键
            unset($data['id']);

            // 更新队伍信息
            $result = $teamModel->where('id', $teamId)->update($data);

            if ($result) {
                return app('json')->success('队伍信息更新成功');
            } else {
                return app('json')->fail('队伍信息更新失败');
            }
        } else {
            // 没有ID则进行新增操作
            $data['user_ids'] = $uid;
            $data['admin_uid'] = $uid;

            $result = $teamModel->save($data);

            if ($result) {
                return app('json')->success('队伍创建成功');
            } else {
                return app('json')->fail('队伍创建失败');
            }
        }
    }

    public function getTeamMember(Request $request)
    {
        $teamId = $request->param('team_id');
        $teamModel = app()->make(\app\model\crud\Team::class);
        $team = $teamModel->where('id',$teamId)->find();
        $baomingModel = app()->make(\app\model\crud\Baoming::class);
        $baomingList = $baomingModel->whereIn('uid',$team['user_ids'])->select();
         return app('json')->success(compact('baomingList'));
    }


    public function joinTeam(Request $request) {
        $uid = $request->uid();
        $teamId = $request->param('team_id');
        $teamModel = app()->make(\app\model\crud\Team::class);
        $tema =$teamModel->where('id',$teamId)->find();
        if($tema) {
            $tema->user_ids = $uid.','.$tema->user_ids;
            $tema->save();
        } else {
            return app('json')->success(100002);
        }
    }

    public function getTeamList(Request $request) {
        try {
            $uid = $request->uid();
            $teamModel = app()->make(\app\model\crud\Team::class);
            $teamList = $teamModel->whereFindInSet('user_ids',$uid)
                ->with('adminBaoming')
                ->select();

            // 格式化数据，包含队长报名信息
            $formattedList = [];
            foreach ($teamList as $team) {
                $formattedList[] = [
                    'id' => $team['id'],
                    'name' => $team['name'],
                    'avatar' => $team['avatar'],
                    'num' => $team['num'],
                    'total_num' => $team['total_num'],
                    'admin_uid' => $team['admin_uid'],
                    'user_ids' => $team['user_ids'],
                    'university' => $team['university'],
                    'admin_baoming' => $team['admin_baoming'] ? [
                        'name' => $team['admin_baoming']['name'] ?? '',
                        'school_card' => $team['admin_baoming']['school_card'] ?? '',
                        'mobile' => $team['admin_baoming']['mobile'] ?? '',
                        'game_id' => $team['admin_baoming']['game_id'] ?? '',
                        'sancang' => $team['admin_baoming']['sancang'] ?? ''
                    ] : null,
                    'create_time' => $team['create_time']
                ];
            }

            return app('json')->success(['teamList' => $formattedList]);
        } catch (\Exception $e) {
            return app('json')->fail('获取我的队伍列表失败：' . $e->getMessage());
        }
    }


    public function getTeamMemberInfo()
    {

    }

    /**
     * 获取所有团队列表
     * @param Request $request
     * @return \think\Response
     */
    public function getAllTeamList(Request $request)
    {
        try {
            $page = $request->param('page', 1);
            $limit = $request->param('limit', 1000);
            $keyword = $request->param('keyword', ''); // 搜索关键词
            $university = $request->param('university', ''); // 大学筛选

            $teamModel = app()->make(\app\model\crud\Team::class);

            // 构建查询条件
            $where = [];
            if (!empty($keyword)) {
                $where[] = ['name', 'like', '%' . $keyword . '%'];
            }
            if (!empty($university)) {
                $where['university'] = $university;
            }

            // 获取总数
            $total = $teamModel->withSearch(array_keys($where), $where)->count();

            // 获取列表数据
            $teamList = $teamModel->withSearch(array_keys($where), $where)
                ->field('id,name,avatar,num,total_num,admin_uid,user_ids,university,create_time')
                ->with('adminBaoming')
                ->order('create_time desc')
                ->page($page, $limit)
                ->select();

            // 格式化数据
            $list = [];
            foreach ($teamList as $team) {
                // 计算当前成员数量
                $memberCount = !empty($team['user_ids']) ? count(explode(',', $team['user_ids'])) : 0;

                $list[] = [
                    'id' => $team['id'],
                    'name' => $team['name'],
                    'avatar' => $team['avatar'],
                    'num' => $team['num'],
                    'total_num' => $team['total_num'],
                    'member_count' => $memberCount,
                    'admin_uid' => $team['admin_uid'],
                    'university' => $team['university'],
                    'admin_baoming' => $team['admin_baoming'] ? [
                        'name' => $team['admin_baoming']['name'] ?? '',
                        'school_card' => $team['admin_baoming']['school_card'] ?? '',
                        'mobile' => $team['admin_baoming']['mobile'] ?? '',
                        'game_id' => $team['admin_baoming']['game_id'] ?? '',
                        'sancang' => $team['admin_baoming']['sancang'] ?? ''
                    ] : null,
                    'create_time' => $team['create_time']
                ];
            }

            return app('json')->success([
                'list' => $list,
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'pages' => ceil($total / $limit)
            ]);
        } catch (\Exception $e) {
            return app('json')->fail('获取团队列表失败：' . $e->getMessage());
        }
    }

    /**
     * 删除队伍
     * @param Request $request
     * @return \think\Response
     */
    public function deleteTeam(Request $request)
    {
        try {
            $uid = $request->param('uid');
            $teamId = $request->param('team_id');
            $currentUid = $request->uid();
            if (!$teamId) {
                return app('json')->fail('队伍ID不能为空');
            }

            $teamModel = app()->make(\app\model\crud\Team::class);
            $team = $teamModel->where('id', $teamId)->find();

            if (!$team) {
                return app('json')->fail('队伍不存在');
            }

            // 检查是否为队长，只有队长才能删除队伍
            if ($team['admin_uid'] != $currentUid) {
                return app('json')->fail('您不是该队伍的队长，无权删除队伍');
            }

            // 删除队伍
//            $userIds = explode(',', $team['user_ids']);
//            $userIds = array_diff($userIds, [$uid]);
//            $team['user_ids'] = implode(',', $userIds);
//            $t = json_encode($team);
//            $arr = json_decode($t, true);
            $result = $teamModel->where('id', $teamId)->delete();

            if ($result) {
                return app('json')->success('队伍删除成功');
            } else {
                return app('json')->fail('队伍删除失败');
            }
        } catch (\Exception $e) {
            return app('json')->fail('删除队伍失败：' . $e->getMessage());
        }
    }
}